package com.literaryfamily.literaryfamily.listen;

import com.literaryfamily.literaryfamily.constant.Constant;
import jakarta.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

/**
 * @author 滑稽/因果报应
 */
@Component
public class IntoListen {
    @Autowired
    ServletContext servletContext;

    /**
     * 监听 Spring 应用上下文刷新事件 (应用启动后)
     */
    @EventListener
    public void onContextRefreshed(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            // 设置输入,输出流的编码格式为 UTF-8
            System.setOut(new PrintStream(System.out, true, StandardCharsets.UTF_8));
            System.setErr(new PrintStream(System.err, true, StandardCharsets.UTF_8));
            // 设置资源存储路径
            Constant.RESOURCE_SAVING_PATH = servletContext.getRealPath("/static/");
        }
    }

    /**
     * 监听 Spring 应用上下文关闭事件
     */
    @EventListener
    public void onContextClosed(ContextClosedEvent event) {
        // 将所有用户状态设置为离线

        // 打印关闭信息

    }
}
